package cmd

import (
	"context"
	"encoding/base64"
	"time"

	"device-admin/config/redis"
	"device-admin/internal/define"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
)

// WaitCmdRsp 等待命令响应
// cmd 命令，cmdSeq 命令序号
func WaitCmdRsp(robotID, cmd, cmdSeq, terminalType string) ([]byte, error) {
	// 订阅主题，等待结果
	timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	pubsub := redis.NewDB().Subscribe(timeoutCtx, define.CMDRsp+robotID+":"+terminalType+":"+cmd+":"+cmdSeq)

	// 删除繁忙标记锁
	defer func() {
		timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		redis.NewDB().Del(timeoutCtx, define.CMDBusy+robotID+":"+terminalType+":"+cmd)
		if pubsub != nil {
			pubsub.Close()
		}
	}()

	// 超时控制
	ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel2()

	for {
		select {
		case <-ctx2.Done():
			return nil, errorx.New("响应超时", -1)
		case data := <-pubsub.Channel():
			dataBytes, _ := base64.StdEncoding.DecodeString(data.Payload)
			return dataBytes, nil
		}
	}
}

// ISBusy 是否繁忙
func ISBusy(robotID, cmd, terminalType string) error {
	timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	success, err := redis.NewDB().SetNX(timeoutCtx, define.CMDBusy+robotID+":"+terminalType+":"+cmd, 1, time.Second*5).Result()
	if err != nil {
		logx.Error(context.Background(), "redis error")
	}
	if !success {
		return errorx.New("系统繁忙，稍后再试", -1)
	}
	return nil
}
